#include "score_summary_dialog.h"
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QTableWidgetItem>
#include <QPushButton>
#include <QMap>
#include <QVector>
#include <algorithm>

ScoreSummaryDialog::ScoreSummaryDialog(QWidget *parent) : QDialog(parent) {
    ui.setupUi(this);
    loadScores();
    connect(ui.btnBack, &QPushButton::clicked, this, &QDialog::accept);
    connect(ui.btnSortAsc, &QPushButton::clicked, this, &ScoreSummaryDialog::sortByScoreAsc);
    connect(ui.btnSortDesc, &QPushButton::clicked, this, &ScoreSummaryDialog::sortByScoreDesc);
}

void ScoreSummaryDialog::loadScores() {
    ui.tableWidget->setRowCount(0);
    QFile file("students.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return;
    QTextStream in(&file);
    QVector<QVector<QString>> data;
    while (!in.atEnd()) {
        QString line = in.readLine().trimmed();
        if (line.isEmpty()) continue;
        QStringList parts = line.split(",");
        if (parts.size() >= 4) {
            QVector<QString> row;
            row << parts[0].trimmed() << parts[1].trimmed() << parts[3].trimmed();
            data.append(row);
        }
    }
    ui.tableWidget->setRowCount(data.size());
    for (int i = 0; i < data.size(); ++i) {
        for (int j = 0; j < 3; ++j) {
            QTableWidgetItem *item = nullptr;
            if (j == 2) {
                item = new QTableWidgetItem();
                item->setData(Qt::EditRole, data[i][j].toInt());
            } else {
                item = new QTableWidgetItem(data[i][j]);
            }
            item->setFlags(item->flags() & ~Qt::ItemIsEditable);
            ui.tableWidget->setItem(i, j, item);
        }
    }
    updateStatistics();
}

void ScoreSummaryDialog::updateStatistics() {
    int rowCount = ui.tableWidget->rowCount();
    if (rowCount == 0) {
        ui.labelMin->setText("最低分：-");
        ui.labelMax->setText("最高分：-");
        ui.tableClassAvg->setRowCount(0);
        return;
    }
    int minScore = 101, maxScore = -1;
    QString minName, minClass, maxName, maxClass;
    QMap<QString, QVector<int>> classScores;
    for (int i = 0; i < rowCount; ++i) {
        QString name = ui.tableWidget->item(i, 0)->text();
        QString clazz = ui.tableWidget->item(i, 1)->text();
        int score = ui.tableWidget->item(i, 2)->text().toInt();
        if (score > 0 && score < minScore) { minScore = score; minName = name; minClass = clazz; }
        if (score > maxScore) { maxScore = score; maxName = name; maxClass = clazz; }
        classScores[clazz].append(score);
    }
    ui.labelMin->setText(QString("最低分：%1（%2 %3）").arg(minScore).arg(minName).arg(minClass));
    ui.labelMax->setText(QString("最高分：%1（%2 %3）").arg(maxScore).arg(maxName).arg(maxClass));
    // 班级平均分
    ui.tableClassAvg->setRowCount(classScores.size());
    int row = 0;
    for (auto it = classScores.begin(); it != classScores.end(); ++it, ++row) {
        int sum = 0;
        int count = 0;
        for (int s : it.value()) {
            if (s > 0) { sum += s; ++count; }
        }
        double avg = (count == 0) ? 0 : (double)sum / count;
        QTableWidgetItem *itemClass = new QTableWidgetItem(it.key());
        QTableWidgetItem *itemAvg = new QTableWidgetItem(QString::number(avg, 'f', 2));
        itemClass->setFlags(itemClass->flags() & ~Qt::ItemIsEditable);
        itemAvg->setFlags(itemAvg->flags() & ~Qt::ItemIsEditable);
        ui.tableClassAvg->setItem(row, 0, itemClass);
        ui.tableClassAvg->setItem(row, 1, itemAvg);
    }
}

void ScoreSummaryDialog::sortByScoreAsc() {
    ui.tableWidget->sortItems(2, Qt::AscendingOrder);
}
void ScoreSummaryDialog::sortByScoreDesc() {
    ui.tableWidget->sortItems(2, Qt::DescendingOrder);
} 